import { Component, OnInit, ViewChild } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'
import { CompanyTreeCarComponent } from '../../shared/companyTreeCar/companyTreeCar.component';

import 'script-loader!select2/dist/js/select2.min.js'
import 'assets/js/select2-zh-CN.js'

declare var $: any
@Component({
  selector: 'sa-slag-vehicle',
  templateUrl: './slag-vehicle.component.html',
  styleUrls: ['./slag-vehicle.css']
})
export class SlagVehicleComponent implements OnInit {
  tableData: any[] = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  searchKey: string = ''
  deviceId: string = ''
  carNumber: string = ''
  isSuccess: string | number = '' // 是否标定成功(0失败 1成功)
  selectedCompanyId: string = ''
  selectedCompanyName: string = ''
  startTime: string = '' //table时间控件
  endTime: string = '' //table时间控件
  outputSuccessEnum = ['正常', '预训练磅单不足', '正式训练磅单不足', '正式训练磅单不足', 'GPS速度都是0'] // 标定结果集:0正常 1预训练磅单不足 2正式训练磅单不足 3GPS速度都是0

  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
    })
  }

  //时间change回调
  getSelectTableTime(val) {
    this.startTime = val.startTime
    this.endTime = val.endTime
  }
  ngOnInit() {
    this.initBinSelect2()
    this.load()
  }
  //table刷新
  refresh() {
    this.load()
  }
  //表格搜索
  table_search() {
    this.curPage = 1
    this.load()
  }
  //初始化加载list数据
  load() {
    let timeCheck = common.correctTimeParams(this.startTime, this.endTime, 0)
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        companyId: this.selectedCompanyId,
        deviceId: this.deviceId,
        startDate: this.startTime,
        endDate: this.endTime,
        isSuccess: this.isSuccess,
        searchKey: common.stringTrim(this.searchKey)
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('deviceCoefHandler/getCalibrationZhatuPage.html', reqdata).subscribe(data => {
      if (data.isSuccess) {
        this.tableData = data.exhibitDatas
        this.totalCount = data.recordCount

        data.exhibitDatas.forEach(item => {
          item.outputSuccessText = this.outputSuccessEnum[item.outputSuccess] || ''
          item.isSuccessText = item.isSuccess === 1 ? '成功' : item.isSuccess === 0 ? '失败' : ''
        })
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }

  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  //公司选中回调
  companySelected(data) {
    this.selectedCompanyId = data.companyId
    this.selectedCompanyName = data.companyName
    this.deviceId = data.deviceId
    this.carNumber = data.carNumber
  }

  // 数据导出
  exportData() {
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        companyId: this.selectedCompanyId,
        deviceId: this.deviceId,
        startDate: this.startTime,
        endDate: this.endTime,
        isSuccess: this.isSuccess,
        searchKey: common.stringTrim(this.searchKey),
        export: '1'
      }
    }
    let timeCheck = common.correctTime(data.parameters, ['dateType', 'export'])
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    common.exprotDataFile(data, 'gridPager', config.BaseURL + 'deviceCoefHandler/getCalibrationZhatuPage.html')
  }

  // 查看输入磅单列表详情
  wbdDataGroupTableData: any[] = []
  showWbdDataGroupListModal(row, modal) {
    this.wbdDataGroupTableData = row.wbdDataGroupList
    modal.show()
  }
  cancelWbdDataGroupListModal(modal) {
    this.wbdDataGroupTableData = []
    this.closeModal(modal)
  }

  // 查看输入的所有载重重量详情
  weightInfoTableData: any[] = []
  showWeightInfoModal(row, modal) {
    this.weightInfoTableData = row.weightInfo
    modal.show()
  }
  cancelWeightInfoModal(modal) {
    this.weightInfoTableData = []
    this.closeModal(modal)
  }

  // GPS异常列表json
  gpsStatusListJsonData: string = ''
  showGpsStatusListJsonModal(row, modal) {
    this.gpsStatusListJsonData = row.gpsStatusListJson
    modal.show()
  }
  cancelGpsStatusListJsonModal(modal) {
    this.gpsStatusListJsonData = ''
    this.closeModal(modal)
  }

  closeModal(modal) {
    modal.hide()
  }


  versionArr = [{
    id: '1',
    name: '第一代'
  }, {
    id: '2',
    name: '第二代'
  }, {
    id: '3',
    name: '808协议'
  }]

  protocolVersion = '2'
  binId = ''; //固件号

  firmwareTableData = []

  firmwareCompanyId = ''

  @ViewChild('firmwareCompany')
  firmwareCompanyComp: CompanyTreeCarComponent
  // 点击弹出设置厂区在线的弹框
  handleFirmwareClick(modal) {
    // 清空公司树
    this.firmwareCompanyComp.resetData();
    const selectObj = $("#binSelect2");
    this.clearSelect2(selectObj);//清除Select中的数据
    this.loadFirmwareTable()
    modal.show();
  }

  loadFirmwareTable() {
    this.jsonApiService.http("deviceCoefHandler/getCalibrationZhatuBinList.html", '').subscribe(data => {
      this.firmwareTableData = data.data;
    })
  }

  handleFirmwareCompanyChange(data) {
    if (this.firmwareCompanyId === data.companyId) return
    this.firmwareCompanyId = data.companyId;
    const selectObj = $("#binSelect2");
    this.clearSelect2(selectObj);//清除Select中的数据
  }

  handleFirmwareCommit() {
    if (!this.binId) {
      this.jsonApiService.message('请选择设备版本');
      return;
    }
    this.jsonApiService.http('deviceCoefHandler/saveCalibrationZhatuBin.html', 'binId=' + this.binId).subscribe(result => {
      this.jsonApiService.message(result.message)
      if (result.success) {
        this.loadFirmwareTable()
      }
    })
  }

  //初始化版本号
  initBinSelect2() {
    const self = this;
    $("#binSelect2").select2({
      language: "zh-CN",
      placeholder: "请选择",
      allowClear: true,
      ajax: {
        url: config.BaseURL + "system/binList.html",
        dataType: 'json',
        delay: 50,
        method: 'POST',
        xhrFields: {
          withCredentials: true
        },
        data: function (params) {
          return {
            searchKey: params.term, // search term
            protocolVersion: '2',
            companyId: self.firmwareCompanyId
          }
        },
        processResults: function (data) {
          const options = data.data
          options.forEach(row => {
            row.text = row.binName
          })
          return {
            results: options //获取查询后的结果
          }
        },
        cache: true
      },
      templateResult: this.formatRepo
    }).on("select2:select", function (e) {
      const data = e.params.data;
      self.binId = data.id;
    });
  }

  //select2 格式回调函数
  formatRepo(state) {
    if (!state.id) {
      return state.text;
    }
    var $state = $('<span><i class="fa fa-file-text-o green"></i>&nbsp;&nbsp;' + state.text + '</span>');
    return $state;
  }

  //清除select2 数据
  clearSelect2(obj) {
    obj.empty();
    obj.prepend("<option value=''>请选择</option>");
  }

}
